﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Transactions;
using WalkingTec.Mvvm.Core;
using HengTong.Model.Db.Hr.Attendance;
using HengTong.Model.Db.Hr.Bill;
using Microsoft.Extensions.DependencyInjection;
using HengTong.Model.Services;
using Microsoft.EntityFrameworkCore;
using TiaoTaoHelper.Models;
using TiaoTaoHelper.Wtm.Interfaces;
using TiaoTaoHelper.Wtm.Models;
using UUIDNext;


namespace HengTong.ViewModel.Daily.SysDailyLeaveRequestBillVms
{
    public partial class SysDailyLeaveRequestBillVm : CrudVm<SysDailyLeaveRequestBill>
    {
        public SysDailyLeaveRequestBillVm()
        {
            SetInclude(x => x.Group);
        }

        protected override void InitVM()
        {
            base.InitVM();
        }

        public override async Task DoAddAsync()
        {
            // 校验必填字段
            if (!Entity.PersonId.HasValue)
            {
                MSD.AddModelError(" ", "员工不能为空");
                return;
            }

            if (!Entity.LeaveType.HasValue)
            {
                MSD.AddModelError(" ", "类型不能为空");
                return;
            }

            if (!Entity.StartTime.HasValue)
            {
                MSD.AddModelError(" ", "开始时间不能为空");
                return;
            }

            if (!Entity.EndTime.HasValue)
            {
                MSD.AddModelError(" ", "结束时间不能为空");
                return;
            }

            using var transactionScope = new TransactionScope(
                TransactionScopeOption.Required,
                new TransactionOptions
                {
                    IsolationLevel = IsolationLevel.ReadCommitted,
                    Timeout = TimeSpan.FromMinutes(10)
                },
                TransactionScopeAsyncFlowOption.Enabled);

            try
            {
                var startDate = Entity.StartTime.Value;
                var endDate = Entity.EndTime.Value;

                // 验证开始时间不能晚于结束时间
                if (startDate > endDate)
                {
                    MSD.AddModelError(" ", "开始时间不能晚于结束时间");
                    return;
                }

                // 第一：重新计算天数
                var totalDays = (endDate.Date - startDate.Date).Days + 1;
                //Entity.Days = totalDays;

                // 校验天数必须为整数（不允许半天或小数天请假）
                if (totalDays <= 0)
                {
                    MSD.AddModelError(" ", "请假出差天数必须大于0天");
                    return;
                }

                // 第二：检查请假时间范围（前后60天）
                var currentDate = DateTime.Now;
                var minDate = currentDate.AddDays(-60);
                var maxDate = currentDate.AddDays(60);

                if (startDate < minDate || endDate > maxDate)
                {
                    MSD.AddModelError(" ", "请假出差时间不能超过当前日期前后60天范围");
                    return;
                }

                // 第三：检查请假期间的考勤记录
                var leaveStartDate = DateOnly.FromDateTime(startDate);
                var leaveEndDate = DateOnly.FromDateTime(endDate);

                // 查询请假期间已有的考勤记录
                var existingRecords = await DC.Set<SysAttendanceRecord>()
                    .AsNoTracking()
                    .Where(x => x.PersonId == Entity.PersonId.Value
                                && x.ShiftDate >= leaveStartDate
                                && x.ShiftDate <= leaveEndDate)
                    .ToListAsync();

                // 检查是否已有考勤结果（参考SysAttendanceRecordBatchVm的逻辑）
                var recordsWithResult = existingRecords
                    .Where(x => x.AttendanceResult != AttendanceResultEnum.未计算)
                    .ToList();

                if (recordsWithResult.Count > 0)
                {
                    var dates = string.Join("、", recordsWithResult
                        .OrderBy(x => x.ShiftDate)
                        .Select(x => x.ShiftDate.ToString("yyyy-MM-dd")));
                    MSD.AddModelError(" ", $"人员{Entity.StaffNo}在{dates}的排班已经有考勤结果，无法申请");
                    return;
                }

                // 新增：检查是否每一天都有排班记录
                // 获取日期范围内的所有日期
                var allDates = new List<DateOnly>();
                for (var date = leaveStartDate; date <= leaveEndDate; date = date.AddDays(1))
                {
                    allDates.Add(date);
                }

                // 找出没有排班记录的日期
                var datesWithoutRecord = allDates
                    .Where(date => !existingRecords.Any(r => r.ShiftDate == date && r.Status == ShiftStatusEnum.正常))
                    .ToList();

                if (datesWithoutRecord.Count > 0)
                {
                    var person = await DC.Set<Model.Db.Hr.SysPerson>()
                        .Where(x => x.ID == Entity.PersonId.Value)
                        .Select(x => x.Name)
                        .FirstOrDefaultAsync();

                    var dates = string.Join("、", datesWithoutRecord.Select(d => d.ToString("yyyy-MM-dd")));
                    MSD.AddModelError(" ",
                        $"人员{person ?? Entity.PersonId.Value.ToString()}在{dates}没有排班记录, 只能对已有排班记录进行请假操作");
                    return;
                }

                // 单据处理逻辑
                if (Entity is IBill bill)
                {
                    Entity.BillStatus = BillStatus.草稿;
                    Entity.WorkflowStatus = WorkflowStatus.待提交;
                    var result = await GenerateCodeAsync();
                    if (result.Code == 200)
                    {
                        Entity.BillCode = result.Data;
                    }
                    else
                    {
                        MSD.AddModelError(" ", $"生成编码异常. {result.Message}");
                        return;
                    }
                }

                Entity.ID = Uuid.NewDatabaseFriendly(Database.SqlServer);
                if (Entity is IBasePoco poco)
                {
                    poco.CreateBy = Entity.StaffNo;
                    poco.UpdateBy = Wtm.LoginUserInfo?.ITCode;
                    poco.CreateTime = DateTime.Now;
                    poco.UpdateTime = DateTime.Now;
                }

                await base.DoAddAsync();

                // 如果所有操作成功，提交事务
                if (MSD.IsValid)
                {
                    transactionScope.Complete();
                }
            }
            catch (Exception e)
            {
                // TransactionScope会自动回滚，无需手动操作
                MSD.AddModelError(" ", $"请假出差申请操作异常: {e.Message}");
            }
        }

        public override async Task DoEditAsync(bool updateAllFields = false)
        {
            if (Entity is IBill { WorkflowStatus: WorkflowStatus.提交中 })
            {
                var raw = await DC.Set<SysDailyLeaveRequestBill>()
                    .AsNoTracking()
                    .FirstOrDefaultAsync(e => e.ID == Entity.ID);
                if (raw.WorkflowStatus != WorkflowStatus.待提交)
                {
                    MSD.AddModelError(" ", "单据已提交审核,请勿重复提交.");
                    return;
                }

                var result = await StartWorkflowAsync("请假出差流程");
                if (result == null) return;
                if (!result.Executed)
                {
                    MSD.AddModelError(" ", $"提交审核异常. {result.Exception?.Message}");
                    return;
                }

                Entity.BillStatus = BillStatus.正文;
                Entity.WorkflowStatus = WorkflowStatus.审核中;
            }

            if (Entity is IBasePoco poco)
            {
                poco.UpdateBy = Wtm.LoginUserInfo?.ITCode;
                poco.UpdateTime = DateTime.Now;
            }

            await base.DoEditAsync(updateAllFields);
        }

        /// <summary>
        /// 必须使用异步事务, 否则工作流引擎会和当前事务冲突
        /// </summary>
        /// <param name="upAllFields"></param>
        public async Task ApproveAsync(bool upAllFields = false)
        {
            using var transactionScope = new TransactionScope(
                TransactionScopeOption.Required,
                new TransactionOptions
                {
                    IsolationLevel = IsolationLevel.ReadCommitted,
                    Timeout = TimeSpan.FromMinutes(10) // 增加超时时间到10分钟
                },
                TransactionScopeAsyncFlowOption.Enabled);
            try
            {
                if (Entity.BillStatus == BillStatus.草稿) Entity.BillStatus = BillStatus.正文;
                Entity.Approver = Wtm.LoginUserInfo?.ITCode;
                Entity.ApprovalTime = DateTime.Now;
                await base.DoEditAsync(upAllFields);
                if (MSD.IsValid)
                {
                    var result = await ContinueWorkflowAsync(ActionName, Remark, "请假出差流程");
                    if (result.Executed == true)
                    {
                        transactionScope.Complete(); // 提交事务
                    }
                    else
                    {
                        MSD.AddModelError(" ", $"工作流执行失败");
                    }
                }
                // 如果到这里，事务会自动回滚
            }
            catch (Exception e)
            {
                // TransactionScope会自动回滚，无需手动操作
                MSD.AddModelError(" ", $"审批操作异常: {e.Message}");
            }
        }

        /// <summary>
        /// 生成编码
        /// </summary>
        /// <returns></returns>
        public async Task<Result<string>> GenerateCodeAsync()
        {
            if (Entity is IBill bill)
            {
                var scope = Wtm.ServiceProvider.CreateScope();
                var service = scope.ServiceProvider.GetRequiredService<CodeGeneratorService>();
                var code = await service.GenerateCodeAsync(Entity.GetType().Name);
                return new Result<string>()
                {
                    Data = code
                };
            }

            return new Result<string>("实体未实现IBill接口");
        }

        /// <summary>
        /// 预测编码
        /// </summary>
        /// <returns></returns>
        public async Task<Result<string>> PredictCodeAsync()
        {
            if (Entity is IBill bill)
            {
                var scope = Wtm.ServiceProvider.CreateScope();
                var service = scope.ServiceProvider.GetRequiredService<CodeGeneratorService>();
                var code = await service.PreviewNextCodeAsync(Entity.GetType().Name);
                return new Result<string>()
                {
                    Data = code
                };
            }

            return new Result<string>("实体未实现IBill接口");
        }

        public override void DoDelete()
        {
            base.DoDelete();
        }
    }
}